package pilates.blogmoon.cn.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import pilates.blogmoon.cn.entity.Action;
import pilates.blogmoon.cn.entity.Category;
import pilates.blogmoon.cn.entity.CategoryActionRel;
import pilates.blogmoon.cn.service.ActionService;
import pilates.blogmoon.cn.mapper.ActionMapper;
import org.springframework.stereotype.Service;
import pilates.blogmoon.cn.service.CategoryActionRelService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 61748
 * @description 针对表【action】的数据库操作Service实现
 * @createDate 2024-04-15 15:24:40
 */
@Service
public class ActionServiceImpl extends ServiceImpl<ActionMapper, Action>
        implements ActionService {

    @Resource
    private CategoryActionRelService categoryActionRelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCategory(Action action) {
        save(action);
        if (CollectionUtils.isEmpty(action.getCategoryId())) {
            return;
        }
        List<CategoryActionRel> actionRelList = action.getCategoryId().stream().map(item -> {
            CategoryActionRel categoryActionRel = new CategoryActionRel();
            categoryActionRel.setActionId(action.getId());
            categoryActionRel.setCategoryId(item);
            return categoryActionRel;
        }).collect(Collectors.toList());
        categoryActionRelService.saveBatch(actionRelList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCategory(Action action) {
        updateById(action);
        categoryActionRelService.remove(Wrappers.<CategoryActionRel>lambdaQuery().eq(CategoryActionRel::getActionId, action.getId()));
        if (CollectionUtils.isEmpty(action.getCategoryId())) {
            return;
        }
        List<CategoryActionRel> actionRelList = action.getCategoryId().stream().map(item -> {
            CategoryActionRel categoryActionRel = new CategoryActionRel();
            categoryActionRel.setActionId(action.getId());
            categoryActionRel.setCategoryId(item);
            return categoryActionRel;
        }).collect(Collectors.toList());
        categoryActionRelService.saveBatch(actionRelList);
    }

    @Override
    public List<Category> selectCategoryListById(Set<Long> idSet) {
        return baseMapper.selectCategoryListById(idSet);
    }
}




